package com.moduls.interfaceFunction.controller;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.moduls.interfaceFunction.core.BusinessResultException;
import com.moduls.interfaceFunction.core.Result;
import com.moduls.interfaceFunction.core.ResultGenerator;
import com.moduls.interfaceFunction.core.SqlMapper;
import com.moduls.interfaceFunction.weixin.pay.utils.GetWxOrderno;

import net.sf.json.JSONObject;


import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class JsonController {
	private final Logger logger = LoggerFactory.getLogger(JsonController.class);
	 @Autowired
	 private SqlSession sqlSession;
	 //@Scope("prototype")
	 //private JSONObject obj_vars;
	 //Lock lock = new ReentrantLock();    //注意这个地方 锁一个请求结束才会请求下一个请求
	 @RequestMapping("/hxapijava/getjson")
	 public Object test(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
		
	     //lock.lock();
		 SqlMapper sqlMapper=new SqlMapper(sqlSession);
		 DESUtil desUtil=new DESUtil();
		 int tokenstatus=0; //0-正常 1-不正常 2-账号禁用
//		 int tokenstatus=1;
//		 String path=request.getQueryString();
//		 String parname=desUtil.decrypt(path);
		 String parname=null;
		 String strVars = request.getParameter("vars");
		 if(strVars==null&&parname!=null) {
			 strVars=parname.split("=")[1];
		 }
		 try {
			 JSONObject obj_vars = JSONObject.fromObject(strVars);
			 String token=obj_vars.optString("token");
			 String sbrand_type=obj_vars.optString("brand_type");
			 String uid=obj_vars.optString("uid"); //登录者id
			 //部分接口允许不做token的校验
			 if(!uid.isEmpty() && !obj_vars.optString("action").equals("c_resubmit_user_set") && !obj_vars.optString("action").equals("s_resubmit_supply_set")
					 && !obj_vars.optString("action").equals("get_upfile_image")) {
				 if(token == "")
				 {
					 Result result=new Result();
					 result.setMessage("会话参数不能为空");
					 return result;
				 }
				 String is_forbid=sqlMapper.public_one_scale(String.format("select is_forbid from p_user where uid=%s and token='%s' ", uid, token));
				if(is_forbid!=null) {
					//账户禁用
					if(is_forbid.equals("1")) {
						tokenstatus=2;
					}
				}
				else
				{
					//会话过期
					tokenstatus=1;
				}
			 }
			if(tokenstatus==0) {
				String straction = obj_vars.optString("action");
				System.out.println(straction);
				HxSupplyApi foo = new HxSupplyApi();
				foo.sqlSessions=sqlSession;
				foo.setObj_vars(obj_vars);
				foo.setBrandType(sbrand_type);
				foo.request=request;
				foo.response=response;
				Class clazz = foo.getClass();
				//获取该类和父类的方法
				//Method m1 = clazz.getDeclaredMethod(straction);
				Method m1 = clazz.getMethod(straction);
				m1.invoke(foo);
				if(parname!=null) {
					return desUtil.encrypt(foo.results.toString());
				}else {
					 return foo.results;
				}
			}else {
				Result result=new Result();
				if(tokenstatus==1) {
					result.setStatus(2);
					result.setMessage("登录过期，请重新登录");
				}else if(tokenstatus==2){
					result.setStatus(3);
					result.setMessage("账号已被禁用，请联系平台");
				}
				return result;
			}
//			return foo.mapoutput;
		} catch (BusinessResultException e) {
			//逻辑异常，在此统一捕获，status为0=
			return e.getResult();
		} catch (InvocationTargetException e) {
			//逻辑异常，在此统一捕获，明确异常原因
			Throwable t = e.getTargetException();
			
			//判断是否业务异常 
			if(t instanceof BusinessResultException)
			{
				return ((BusinessResultException)t).getResult();
			}
			
			return t.toString();
		} catch (Exception e) {
			Result result=new Result();
			result.setMessage("接口调用出错");
			return result;
			// TODO Auto-generated catch block
//			e.printStackTrace();
		}finally {
			 //lock.unlock();
		}
//		 return null;
	 }
	 
	 @RequestMapping("/hxapijava/getbackjson")
	 public Object back(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
		
		 request.setCharacterEncoding("UTF-8");  
		 response.setCharacterEncoding("UTF-8");  
		 response.setContentType("text/html;charset=UTF-8");  
		 response.setHeader("Access-Control-Allow-Origin", "*"); 
		 
	     //lock.lock();
		 SqlMapper sqlMapper=new SqlMapper(sqlSession);
		 DESUtil desUtil=new DESUtil();
		 int tokenstatus=0; //0-正常 1-不正常 2-账号禁用
//		 int tokenstatus=1;
//		 String path=request.getQueryString();
//		 String parname=desUtil.decrypt(path);
		 String parname=null;
		 String strVars = request.getParameter("vars");
		 if(strVars==null&&parname!=null) {
			 strVars=parname.split("=")[1];
		 }
		 try {
			 JSONObject obj_vars = JSONObject.fromObject(strVars);
			 String mid=obj_vars.optString("mid"); //登录者id
			 //部分接口允许不做token的校验
			 if(mid != null && !mid.isEmpty() && !obj_vars.optString("action").equals("get_upfile_image")) {
				 String is_forbid=sqlMapper.public_one_scale(String.format("select is_forbid from hx_member where member_id=%s ", mid));
				if(is_forbid!=null) {
					//账户禁用
					if(is_forbid.equals("1")) {
						tokenstatus=2;
					}
				}
				else
				{
					//会话过期
					tokenstatus=1;
				}
			 }
			if(tokenstatus==0) {
				String straction = obj_vars.optString("action");
				System.out.println(straction);
				HxSupplyApi foo = new HxSupplyApi();
				foo.sqlSessions=sqlSession;
				foo.setObj_vars(obj_vars);
				foo.request=request;
				foo.response=response;
				Class clazz = foo.getClass();
				//获取该类和父类的方法
				//Method m1 = clazz.getDeclaredMethod(straction);
				Method m1 = clazz.getMethod(straction);
				m1.invoke(foo);
				if(parname!=null) {
					return desUtil.encrypt(foo.results.toString());
				}else {
					 return foo.results;
				}
			}else {
				Result result=new Result();
				if(tokenstatus==1) {
					result.setStatus(2);
					result.setMessage("登录过期，请重新登录");
				}else if(tokenstatus==2){
					result.setStatus(3);
					result.setMessage("账号已被禁用，请联系平台");
				}
				return result;
			}
//			return foo.mapoutput;
		} catch (BusinessResultException e) {
			//逻辑异常，在此统一捕获，status为0=
			return e.getResult();
		} catch (InvocationTargetException e) {
			//逻辑异常，在此统一捕获，明确异常原因
			Throwable t = e.getTargetException();
			
			//判断是否业务异常 
			if(t instanceof BusinessResultException)
			{
				return ((BusinessResultException)t).getResult();
			}
			
			return t.toString();
		} catch (Exception e) {
			Result result=new Result();
			result.setMessage("接口调用出错");
			return result;
			// TODO Auto-generated catch block
//			e.printStackTrace();
		}finally {
			 //lock.unlock();
		}
//		 return null;
	 }
	 
	 @RequestMapping("/wxapijava/zfbcallback")//支付宝回调
	 public void zfbcallback(HttpServletRequest request) throws UnsupportedEncodingException, SQLException{
		 SqlMapper sqlMapper=new SqlMapper(sqlSession);
		 Map<String,String> params = new HashMap<String,String>();
		 Map requestParams = request.getParameterMap();

		 for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
		 String name = (String) iter.next();
		 String[] values = (String[]) requestParams.get(name);
		 String valueStr = "";
		 for (int i = 0; i < values.length; i++) {
		 valueStr = (i == values.length - 1) ? valueStr + values[i]:valueStr + values[i] + ",";
		 }
		//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
		//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
		params.put(name, valueStr);
		}
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
			//商户订单号	
			String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8"); 
			//支付宝交易号	
			String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
			//交易状态
			String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
			 System.out.println(out_trade_no+"||"+trade_no+"||"+trade_status);
			if(trade_status.equals("TRADE_FINISHED")||trade_status.equals("TRADE_SUCCESS")){
				if(out_trade_no!=null&&trade_no!=null) {
					int uid=0;
					String reward_amount="";
					Map<String, Object> details=sqlMapper.public_one_detail("select business_id,reward_type,amount,status from p_reward where reward_no='"+out_trade_no+"'");
					String datatype=details.get("reward_type").toString();//1发布任务打赏；2即时点工打赏；3用户评价打赏；4服务商评价打赏
					Map<String, String> maps=new HashMap<>();
					if(!details.get("status").equals(2)) {
					switch (datatype) {
					case "1":
						sqlMapper.insert_or_update("m_task", new HashMap<String, String>() {
							{
								put("status", "2");
							}
						}, "task_id="+details.get("business_id"));//更新任务状态
						 uid=Integer.parseInt(sqlMapper.public_one_scale("select uid from m_task where task_id="+details.get("business_id"))) ;
						 reward_amount=sqlMapper.public_one_scale("select reward_amount from p_user where uid="+uid);
						 maps.put("reward_amount", String.valueOf((Double.parseDouble(reward_amount)+Double.parseDouble(details.get("amount").toString()))));
						 sqlMapper.insert_or_update("p_user",maps, "uid="+uid);//更新打赏金额
						break;
						
					case "2":
						sqlMapper.insert_or_update("m_point", new HashMap<String, String>() {
							{
								put("status", "2");
							}
						}, "point_id="+details.get("business_id"));
						uid=Integer.parseInt(sqlMapper.public_one_scale("select uid from m_point where point_id="+details.get("business_id"))) ;
						reward_amount=sqlMapper.public_one_scale("select reward_amount from p_user where uid="+uid);
						 maps.put("reward_amount", String.valueOf((Double.parseDouble(reward_amount)+Double.parseDouble(details.get("amount").toString()))));
						 sqlMapper.insert_or_update("p_user",maps, "uid="+uid);//更新打赏金额
						break;
						
					case "3":
						sqlMapper.insert_or_update("m_evaluation", new HashMap<String, String>() {
							{
								put("status", "2");
							}
						}, "evl_id="+details.get("business_id"));
						sqlMapper.insert_or_update("m_order", new HashMap<String, String>() {
							{
								put("is_user_pay", "2");
							}
						}, "oid="+sqlMapper.public_one_scale("select oid from m_evaluation where evl_id="+details));
						uid=Integer.parseInt(sqlMapper.public_one_scale("select uid from m_evaluation where evl_id="+details.get("business_id"))) ;
						reward_amount=sqlMapper.public_one_scale("select reward_amount from p_user where uid="+uid);
						 maps.put("reward_amount", String.valueOf((Double.parseDouble(reward_amount)+Double.parseDouble(details.get("amount").toString()))));
						 sqlMapper.insert_or_update("p_user",maps, "uid="+uid);//更新打赏金额
						break;
						
					case "4":
						sqlMapper.insert_or_update("s_evaluation", new HashMap<String, String>() {
							{
								put("status", "2");
							}
						}, "evl_id="+details.get("business_id"));
						sqlMapper.insert_or_update("m_order", new HashMap<String, String>() {
							{
								put("is_provider_pay", "2");
							}
						}, "oid="+sqlMapper.public_one_scale("select oid from s_evaluation where evl_id="+details.get("business_id")));
						uid=Integer.parseInt(sqlMapper.public_one_scale("select pid as uid from s_evaluation where evl_id="+details.get("business_id"))) ;
						reward_amount=sqlMapper.public_one_scale("select IFNULL(reward_amount,0) reward_amount from s_provider where pid="+uid);
						 maps.put("reward_amount", String.valueOf((Double.parseDouble(reward_amount)+Double.parseDouble(details.get("amount").toString()))));
						 sqlMapper.insert_or_update("s_provider",maps, "pid="+uid);//更新打赏金额
						break;
					}
					Map<String,String> map=new HashMap<>();
					map.put("trade_no",trade_no);
					map.put("pay_time",sqlMapper.public_getcurrenttime());
					map.put("pay_type","1");
					map.put("status", "2");
					sqlMapper.insert_or_update("p_reward",map, "reward_no='"+out_trade_no+"'");
					}
				}
			}
	 }
	 @RequestMapping("/wxapijava/wxcallback")//微信回调
	 public String wxcallback(HttpServletRequest request,HttpServletResponse response) throws Exception{
		 Map<String, String> maps=new HashMap<>();
		 SqlMapper sqlMapper=new SqlMapper(sqlSession);
		 request.setCharacterEncoding("UTF-8");  
		 response.setCharacterEncoding("UTF-8");  
		 response.setContentType("text/html;charset=UTF-8");  
		 response.setHeader("Access-Control-Allow-Origin", "*");   
		  BufferedReader reader = request.getReader();
		  String line = "";
		  String xmlString = null;
		  StringBuffer inputString = new StringBuffer();
	        while ((line = reader.readLine()) != null) {
	            inputString.append(line);
	        }
	        xmlString = inputString.toString();
	        request.getReader().close();
		  Map map =  new GetWxOrderno().doXMLParse(xmlString);  
		  if(map!=null) {
		  System.out.println(map.toString());
		     String result_code=map.get("result_code").toString();  
			 String out_trade_no  = map.get("out_trade_no").toString();  
			 String trade_no  =  map.get("transaction_id").toString();  
			 if(result_code.equals("SUCCESS")){ 
				 if(out_trade_no!=null&&trade_no!=null) {
						int uid=0;
						String reward_amount="";
						Map<String, Object> details=sqlMapper.public_one_detail("select business_id,reward_type,amount,status from p_reward where reward_no='"+out_trade_no+"'");
						String datatype=details.get("reward_type").toString();//1发布任务打赏；2即时点工打赏；3用户评价打赏；4服务商评价打赏
						Map<String, String> mapss=new HashMap<>();
						if(!details.get("status").equals(2)) {
						switch (datatype) {
						case "1":
							sqlMapper.insert_or_update("m_task", new HashMap<String, String>() {
								{
									put("status", "2");
								}
							}, "task_id="+details.get("business_id"));//更新任务状态
							 uid=Integer.parseInt(sqlMapper.public_one_scale("select uid from m_task where task_id="+details.get("business_id"))) ;
							 reward_amount=sqlMapper.public_one_scale("select reward_amount from p_user where uid="+uid);
							 mapss.put("reward_amount", String.valueOf((Double.parseDouble(reward_amount)+Double.parseDouble(details.get("amount").toString()))));
							 sqlMapper.insert_or_update("p_user",mapss, "uid="+uid);//更新打赏金额
							break;
							
						case "2":
							sqlMapper.insert_or_update("m_point", new HashMap<String, String>() {
								{
									put("status", "2");
								}
							}, "point_id="+details.get("business_id"));
							uid=Integer.parseInt(sqlMapper.public_one_scale("select uid from m_point where point_id="+details.get("business_id"))) ;
							reward_amount=sqlMapper.public_one_scale("select reward_amount from p_user where uid="+uid);
							 mapss.put("reward_amount", String.valueOf((Double.parseDouble(reward_amount)+Double.parseDouble(details.get("amount").toString()))));
							 sqlMapper.insert_or_update("p_user",mapss, "uid="+uid);//更新打赏金额
							break;
							
						case "3":
							sqlMapper.insert_or_update("m_evaluation", new HashMap<String, String>() {
								{
									put("status", "2");
								}
							}, "evl_id="+details.get("business_id"));
							sqlMapper.insert_or_update("m_order", new HashMap<String, String>() {
								{
									put("is_user_pay", "2");
								}
							}, "oid="+sqlMapper.public_one_scale("select oid from m_evaluation where evl_id="+details.get("business_id")));
							uid=Integer.parseInt(sqlMapper.public_one_scale("select uid from m_evaluation where evl_id="+details.get("business_id"))) ;
							reward_amount=sqlMapper.public_one_scale("select reward_amount from p_user where uid="+uid);
							 mapss.put("reward_amount", String.valueOf((Double.parseDouble(reward_amount)+Double.parseDouble(details.get("amount").toString()))));
							 sqlMapper.insert_or_update("p_user",mapss, "uid="+uid);//更新打赏金额
							break;
							
						case "4":
							sqlMapper.insert_or_update("s_evaluation", new HashMap<String, String>() {
								{
									put("status", "2");
								}
							}, "evl_id="+details.get("business_id"));
							sqlMapper.insert_or_update("m_order", new HashMap<String, String>() {
								{
									put("is_provider_pay", "2");
								}
							}, "oid="+sqlMapper.public_one_scale("select oid from s_evaluation where evl_id="+details.get("business_id")));
							uid=Integer.parseInt(sqlMapper.public_one_scale("select pid as uid from s_evaluation where evl_id="+details.get("business_id"))) ;
							reward_amount=sqlMapper.public_one_scale("select IFNULL(reward_amount,0) reward_amount from s_provider where pid="+uid);
							 mapss.put("reward_amount", String.valueOf((Double.parseDouble(reward_amount)+Double.parseDouble(details.get("amount").toString()))));
							 sqlMapper.insert_or_update("s_provider",mapss, "pid="+uid);//更新打赏金额
							break;
						}
						  maps=new HashMap<>();
							maps.put("trade_no",trade_no);
							maps.put("pay_time",sqlMapper.public_getcurrenttime());
							maps.put("pay_type","2");
							maps.put("status", "2");
							sqlMapper.insert_or_update("p_reward",maps,"reward_no='"+out_trade_no+"'");
						}
						 return returnXML(trade_no);
					}else {
						 return returnXML("FAIL");
					 }
			 }else {
				 return returnXML("FAIL");
			 }
		  }else {
				 return returnXML("FAIL");
			 }
		 } 
	 private String returnXML(String return_code) {

	        return "<xml><return_code><![CDATA["

	                + return_code

	                + "]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
	    }
}
